import ruleService, { type PageListReq } from "@/api/services/tool/ruleService";
import TableDictTag from "@/components/grid/TableDictTag";
import { TableToolbar } from "@/components/grid/TableToolbar";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import { Button, Card, Drawer, Form, Input, InputNumber, Modal, Select, Space } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import type { AutoCodePart, AutoCodeRule } from "./entity";
import RulePart from "./rulePart";

const { TextArea } = Input;

export default function AutoCodeRulePage() {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		ruleCode: undefined,
		ruleName: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<AutoCodeRule[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<AutoCodeRule | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

  const [partRuleId, setPartRuleId] = useState<React.Key>();
  const [partList, setPartList] = useState<AutoCodePart[]>([])
  const [partVisible, setPartVisible] = useState(false);
  const [partTableLoading, setPartTableLoading] = useState(false);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const isPaddedOptions = useDictionary("system_true_false");
  const enableFlagOptions = useDictionary("system_true_false");

	const columns: ColumnsType<AutoCodeRule> = [
		{
			title: "规则编码",
			width: 120,
			key: "ruleCode",
			dataIndex: "ruleCode",
      render: (_, record) => <Button color="primary" variant="link" onClick={() => handleEditPart(record)}>{record.ruleCode}</Button>
		},
		{
			title: "规则名称",
			width: 120,
			key: "ruleName",
			dataIndex: "ruleName",
		},
		{
			title: "最大长度",
			width: 120,
			key: "maxLength",
			dataIndex: "maxLength",
		},
		{
			title: "是否补齐",
			width: 120,
			key: "isPadded",
			dataIndex: "isPadded",
			render: (_, record) => <TableDictTag dictCode="system_true_false" value={record.isPadded} />,
		},
		{
			title: "补齐字符",
			width: 120,
			key: "paddedChar",
			dataIndex: "paddedChar",
		},
		{
			title: "补齐方式",
			width: 120,
			key: "paddedMethod",
			dataIndex: "paddedMethod",
		},
		{
			title: "是否启用",
			width: 120,
			key: "enableFlag",
			dataIndex: "enableFlag",
			render: (_, record) => <TableDictTag dictCode="system_true_false" value={record.enableFlag} />,
		},
		{
			title: "备注",
			width: 120,
			key: "description",
			dataIndex: "description",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);

	const filteredColumns = useMemo(() => {
		return [...columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation")].sort(
			(a, b) => {
				const originalIndex = columns.findIndex((c) => c.key === a.key);
				const targetIndex = columns.findIndex((c) => c.key === b.key);
				return originalIndex - targetIndex;
			},
		);
	}, [selectedValues]);

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		ruleService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (autoCodeRule: AutoCodeRule) => {
		setEditingData(autoCodeRule);
		form.setFieldsValue(autoCodeRule);
		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (autoCodeRule: AutoCodeRule) => {
		setEditingData(autoCodeRule);
		form.setFieldsValue(autoCodeRule);
		setIsView(true);
		setDrawerVisible(true);
	};

  //编辑组成部分
  const handleEditPart = (rule: AutoCodeRule) => {
    if(rule.id) {
      setPartVisible(true)
      setPartTableLoading(true)
      setPartRuleId(rule.id);
      ruleService.getRulePart(rule.id).then(res => {
        setPartList(res);
      }).catch(error => {
        toast.error(error.message)
      }).finally(()=>{
        setPartTableLoading(false)
      })
    }
  }
  const handlePartClose = () => {
    setPartVisible(false);
    setPartRuleId(undefined);
  }
  const savePart = () => {
    ruleService.savePart(partList).then(res => {
      setPartVisible(false);
      setPartRuleId(undefined);
    }).catch(error => {
      toast.error(error.message);
    })
  }

	//提交表单数据
	const handleSubmit = async (values) => {
		try {
			setLoading(true);
			if (editingData) {
				await ruleService.update({ ...values, id: editingData.id });
				toast.success("更新编码生成规则成功");
			} else {
				await ruleService.add(values);
				toast.success("创建编码生成规则成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(error.message);
		} finally {
			setLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await ruleService.remove(selectedRowKeys);
			toast.success("删除编码生成规则成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	return (
		<>
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="ruleCode" label="规则编码">
						<Input placeholder="请输入规则编码" allowClear />
					</Form.Item>
					<Form.Item name="ruleName" label="规则名称">
						<Input placeholder="请输入规则名称" allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<div className="flex justify-between mb-4">
					<div className="flex gap-2">
						<Button type="primary" onClick={handleAdd}>
							新增
						</Button>
						<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
							删除
						</Button>
					</div>
					<TableToolbar
						onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="id"
					size={tableSize}
					scroll={{ x: "max-content", y: tableScrollY }}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={filteredColumns}
					dataSource={list}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑编码生成规则" : "新增编码生成规则"}
				width={480}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item name="ruleCode" label="规则编码">
						<Input placeholder="请输入规则编码" allowClear disabled={isView || editingData!=null} />
					</Form.Item>
					<Form.Item name="ruleName" label="规则名称">
						<Input placeholder="请输入规则名称" allowClear/>
					</Form.Item>
					<Form.Item name="maxLength" label="最大长度">
						<InputNumber placeholder="请输入最大长度" style={{width: "100%"}}/>
					</Form.Item>
					<Form.Item name="isPadded" label="是否补齐">
						<Select options={isPaddedOptions} allowClear/>
					</Form.Item>
					<Form.Item name="paddedChar" label="补齐字符">
						<Input placeholder="请输入补齐字符" allowClear/>
					</Form.Item>
					<Form.Item name="paddedMethod" label="补齐方式">
						<Input placeholder="请输入补齐方式" allowClear/>
					</Form.Item>
					<Form.Item name="enableFlag" label="是否启用">
						<Select options={enableFlagOptions} allowClear/>
					</Form.Item>
					<Form.Item name="description" label="备注">
						<TextArea />
					</Form.Item>
				</Form>
			</Drawer>

      {/* 规则组成部分 */}
      <Modal
				title="规则组成部分"
				open={partVisible}
				width="100%"
				style={{ top: 0, maxWidth: "98vw", padding: 10 }}
				styles={{
					body: { height: "calc(100vh - 200px)", overflow: "auto", padding: "10px 24px" },
					content: { maxWidth: "100vw", overflow: "hidden" },
					header: { padding: "16px 24px" },
					footer: { padding: "10px 24px" },
				}}
				onCancel={handlePartClose}
        footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handlePartClose}>取消</Button>
						<Button type="primary" onClick={() => savePart()}>
              确定
            </Button>
					</div>
				}
			>
        <RulePart ruleId={partRuleId} loading={partTableLoading} partList={partList} setPartList={setPartList}/>
			</Modal>
		</>
	);
}
